package lambda;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import org.junit.jupiter.api.Test;
// 如果接口中只有一个抽象方法就可以使用lambda风格
public class Lambda {
	@Test
	public void supplier() {
		//1.匿名内部类
		Supplier<Integer> sup = new Supplier<Integer>() {
			@Override
			public Integer get() {
				Random rand = new Random();
				return rand.nextInt(100);
			}
		};
		Integer num = sup.get();
		System.out.println(num);
		
		//2.修改lambda上：1省new接口 2.省方法头
		Supplier<Integer> sup2 = ()->{
			Random rand = new Random();
			return rand.nextInt(100);
		};
		//3.修改lambda上：2省return关键字，省{}
		Supplier<Integer> sup3 = ()->new Random().nextInt(100);
		Integer num2 = sup3.get();
		System.out.println(num2);
	}
	
	@Test
	public void consumer() {
		Consumer<String> con = new Consumer<String>() {
			@Override
			public void accept(String t) {
				System.out.println(t);
			}
		};
		con.accept("hello kitty");
		
		// 参数类型可以省
		Consumer<String> con2 = (t)->System.out.println(t);
		con2.accept("kitty hello");
	}
	
	@Test
	public void function() {
		Function<Double,Double> fun = new Function<Double,Double>() {
			@Override
			public Double apply(Double t) {
				return (double) Math.round(t); //四舍五入取整
			}
		};
		Double num = fun.apply(1.55);
		System.out.println(num);
		
		Function<Double,Double> fun2 = (t)->(double) Math.round(t);
		Double num2 = fun2.apply(1.55);
		System.out.println(num2);
	}
	
	@Test
	public void predicate() {
		Predicate<String> pre = new Predicate<String>() {
			@Override
			public boolean test(String t) {
				return t.length() > 6;
			}
		};
		
		boolean test = pre.test("hello world");
		System.out.println(test);
		
		Predicate<String> pre2 = (t)->t.length() > 6;
		boolean test2 = pre2.test("hell");
		System.out.println(test2);
	}
	
	@Test
	public void comparator() {
		List<Integer> list = new ArrayList<>();
		Collections.addAll(list, 123,34,53,61,144,624);
		
		list.sort((o1,o2)-> o2 - o1);
		
		System.out.println(list);
	}
	
}
